//创建自调用函数,避免命名冲突
(function(){
	var that;
	function Game(map){
	this.food=new Food();
	this.snake=new Snake();
	this.map=map;
	that=this;
}
//把蛇对象和食物对象渲染到map上
Game.prototype.start=function(){
	this.food.render(this.map);
	this.snake.render(this.map);
	runSnake();
	bindKey();
}
function bindKey(){
	document.addEventListener('keydown',function(e){
		switch (e.keyCode){
			case 37:
			that.snake.direction='left';
			break;
			case 38:
			that.snake.direction='top';
			break;
			case 39:
			that.snake.direction='right';
			break;
			case 40:
			that.snake.direction='bottom';
			break;
		}
	},false)
}
function runSnake(){
	var timer=setInterval(function(){
	that.snake.move(that.food,that.map);
	that.snake.render(that.map);
	//当蛇遇到边界游戏结束
	//获取蛇头的坐标
	var maxX=that.map.offsetWidth/that.snake.width-1;
	var maxY=that.map.offsetHeight/that.snake.height-1;
	var headX=that.snake.body[0].x;
	var headY=that.snake.body[0].y;
	if(headX<=0||headX>=maxX){
		clearInterval(timer);
		setTimeout(function(){
			alert('gameover')
		},100)
	}

	if(headY<=0||headY>=maxY){
		clearInterval(timer);
		setTimeout(function(){
			alert('gameover');
		},100)
	}
	},1000)
	
}
window.Game=Game;
})();

